package com.example.springbootsfzy.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class OSSUtil {
    // yourEndpoint,填写Bucket所在地域对应的Endpoint。
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 填写Bucket名称。
    private static String bucketName = "gmhoss";
    // 填写Object的完整路径。Object完整路径中不能包含Bucket名称。
    private static String objectName = "text/";

    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。
    private static String accessKeyId = "LTAI5t6eYfp7iGUQeMpsQT9c";
    private static String accessKeySecret = "CoKMW8A35r0qfTcJ7oi3SFr3NiK50o";

    // 文件url前缀
    private static String furl = "https://gmhoss.oss-cn-beijing.aliyuncs.com/";

    // 文件上传方法
    public  static   String   upload(String fileName, InputStream in){
        // 组合objectName
     String objectNameUrl= objectName + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传
        PutObjectResult re = ossClient.putObject(bucketName, objectNameUrl, in);
        //关闭连接
        ossClient.shutdown();

        // 返回文件的url
//        https://xiao0214.oss-cn-hangzhou.aliyuncs.com/tx/....
        return furl+objectNameUrl;
    }

    //文件下载方法
    public  static   void   download(String fileName, OutputStream out) throws IOException {
        // 组合objectName
       String objectNameUrl = objectName + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 下载
        OSSObject object = ossClient.getObject(bucketName, objectNameUrl);
        InputStream in = object.getObjectContent();

        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = in.read(bytes))!= -1){
            out.write(bytes,0,len);
        }
        out.close();
        in.close();

        //关闭连接
        ossClient.shutdown();
    }
}